//
//  XLNetworkTools.swift
//  WeiBo
//
//  Created by macbook on 16/10/18.
//  Copyright © 2016年 buWangChuXing. All rights reserved.
//

import UIKit

import AFNetworking


enum MethodType:String {
    case GET = "GET"
    case POST = "POST"
}

class XLNetworkTools: AFHTTPSessionManager {
    
    static let shardTools:XLNetworkTools = {
    
        let tools = XLNetworkTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    
    func request(mestod:MethodType,urlString:String,parameters:AnyObject?,success:(response:AnyObject?)->(),failure:(error:NSError)->())
    {
        
        if mestod == .GET {
            
            self.GET(urlString, parameters: parameters, progress: nil, success: { (_, resposet) in
                
                success(response: resposet)
                
                }, failure: { (_, error) in
                    
                    failure(error: error)
            })
        }else
        {
            self.POST(urlString, parameters: parameters, progress: nil, success: { (_, respose) in
                
                success(response: respose)
                }, failure: { (_, error) in
                    
                    failure(error: error)
            })
        }
      
  }

}

extension XLNetworkTools
{
    //q请求token
    func oauthLoadUserAccout(code:String,success:(reponse:AnyObject?)->(),faile:(error:NSError?)->())
    {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let parameters = [
            "client_id":APPKEY,
            "client_secret":APPSECRET,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":REDIRECT_URI,
        
        ]
        
        self.request(.POST, urlString: urlString, parameters: parameters, success: success, failure: faile)
        
    }
    
    //获得个人信息
    func loadUserInfo(userAccount:XLUserAccout,succeess:(reponse:AnyObject?)->(),faile:(error:NSError)->())
    {
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let param = [
            "access_token":userAccount.access_token!,
            "uid":userAccount.uid!
            ]
        self.request(.GET, urlString: urlString, parameters: param, success: succeess, failure: faile)
    }
    
}

extension XLNetworkTools
{
    func homeLoadStatusData(success:(reponse:AnyObject?)->(),faile:(error:NSError)->())
    {
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        let param = ["access_token":XLUserAccountTools.shardTools.accessToken!]
        self.request(.GET, urlString: urlString, parameters: param
            , success: success, failure: faile)
    }
}









